package com.wiwf.model.task.service.impl;

import com.wiwf.model.task.service.TaskOutHandlerService;
import com.wiwf.model.task.thread.OutHandlerThread;
import com.wiwf.model.task.bean.TaskerCommand;
import com.wiwf.model.task.service.TaskExecService;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 命令执行服务
 *
 * @author kehui
 */
@Service
public class TaskExecServiceImpl implements TaskExecService {

    @Override
    public Process exec(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        return runtime.exec(command);
    }

    @Override
    public Boolean stop(Process process) {
        if (process != null) {
            process.destroy();
            return true;
        }
        return false;
    }

    @Override
    public Boolean stop(Thread outHandler) {
        if (outHandler != null && outHandler.isAlive()) {
            return true;
        }
        return false;
    }

    @Override
    public void stopTasker(TaskerCommand tasker) {
        if(tasker != null) {
            stop(tasker.getThread());
            stop(tasker.getProcess());
        }
    }

    @Override
    public TaskerCommand createTasker(String id, String command, TaskOutHandlerService ohm) throws IOException {
        // 执行本地命令获取任务主进程
        Process process = exec(command);
        // 创建输出线程
        OutHandlerThread outHandler = OutHandlerThread.create(process.getErrorStream(), id, ohm);

        TaskerCommand tasker = new TaskerCommand(id,command, process, outHandler);

        return tasker;
    }

}
